//
//  TimerAddViewController.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/10/25.
//

import UIKit
import SVProgressHUD

class TimerAddViewController: RoundCornerTableViewController {
    
    var customTimer: CustomTimer?
    
    private var datas = [BaseSectionModel]()
    private var picker: TimePickerView?
    private var viewModel: TimerAddViewModel!
    private var layer: CAShapeLayer!
    private var timeType: TimeType = .start
    private var didSelectIndexPath: IndexPath?

    override func viewDidLoad() {
        super.viewDidLoad()

        setupTableView()
        viewModel = TimerAddViewModel(customTimer: customTimer)
        loadData()
    }
    
    // MARK: - private
    
    @objc private func loadData() {
        datas = viewModel.loadData()
        tableView.reloadData()
    }
    
    @objc private func saveTimer() {
        if viewModel.save() {
            SVProgressHUD.showSuccess(withStatus: "添加成功")
            navigationController?.popViewController(animated: true)
        }
    }
    
    private func setupTableView() {
        tableView.separatorStyle = .none
        tableView.sectionHeaderHeight = 15
        tableView.sectionFooterHeight = 10
        tableView.backgroundColor = .clear
        
        tableView.register(UINib(nibName: kTimerPickerCell, bundle: nil), forCellReuseIdentifier: kTimerPickerCell)
        tableView.register(UINib(nibName: kSettingArrowCell, bundle: nil), forCellReuseIdentifier: kSettingArrowCell)
        tableView.register(UINib(nibName: kSettingColorCell, bundle: nil), forCellReuseIdentifier: kSettingColorCell)
        tableView.register(UINib(nibName: kSettingOnlyInputCell, bundle: nil), forCellReuseIdentifier: kSettingOnlyInputCell)
        tableView.register(UINib(nibName: kTimerTypeSegmentedCell, bundle: nil), forCellReuseIdentifier: kTimerTypeSegmentedCell)
        
//        let tap = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboard))
//        tap.numberOfTapsRequired = 1
//        tableView.addGestureRecognizer(tap)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(self.saveTimer))
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.loadData), name: .refreshTimerAddController, object: nil)
        
        if let customTimer = customTimer {
            if let color = customTimer.color {
                view.backgroundColor = color
            }
        }
    }
    
    @objc private func hideKeyboard() {
        view.endEditing(true)
    }
    
    private func showTimePickerView() {
        picker = TimePickerView()
        picker?.delegate = self
        picker?.showView()
    }
}

extension TimerAddViewController {
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas[section].items.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellModel = datas[indexPath.section].items[indexPath.row]
        return cellModel.rowHeight == 0 ? 50 : cellModel.rowHeight
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
        return view
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellModel = datas[indexPath.section].items[indexPath.row]
        if cellModel is SettingOnlyInputCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: kSettingOnlyInputCell, for: indexPath) as! SettingOnlyInputCell
            cell.model = cellModel as? SettingOnlyInputCellModel
            return cell
        } else if cellModel is TimerTypeSegmentedCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: kTimerTypeSegmentedCell, for: indexPath) as! TimerTypeSegmentedCell
            cell.model = cellModel as? TimerTypeSegmentedCellModel
            return cell
        } else if cellModel is SettingArrowCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: kSettingArrowCell, for: indexPath) as! SettingArrowCell
            cell.model = cellModel as? SettingArrowCellModel
            return cell
        } else if cellModel is TimerPickerCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: kTimerPickerCell, for: indexPath) as! TimerPickerCell
            cell.model = cellModel as? TimerPickerCellModel
            return cell
        } else if cellModel is SettingColorCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: kSettingColorCell, for: indexPath) as! SettingColorCell
            cell.model = cellModel as? SettingColorCellModel
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: kSettingArrowCell, for: indexPath) as! SettingArrowCell
            return cell
        }
    }
    
//    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//        let cornerCell = cell as! RoundCornerCell
//        
//        // 清除状态，否则复用是会有问题
//        cornerCell.layer.mask = nil
//        cornerCell.rectCorner = []
//        let row = indexPath.row
//        // 最后一行
//        let lastRow = tableView.numberOfRows(inSection: indexPath.section) - 1
//        // 如果是第一行也是最后一行,只有一个cell四个圆角
//        if row == 0 && row == lastRow {
//            cornerCell.rectCorner = .allCorners
//        } else if row == 0 { // 第一行
//            cornerCell.rectCorner = [.topLeft, .topRight]
//        } else if row == lastRow { // 最后一行
//            cornerCell.rectCorner = [.bottomLeft, .bottomRight]
//        }
//    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        super.tableView(tableView, didSelectRowAt: indexPath)
        
        hideKeyboard()
        
        self.didSelectIndexPath = indexPath
        let cellModel = datas[indexPath.section].items[indexPath.row]
        if cellModel is BaseSettingCellModel {
            let model = cellModel as! BaseSettingCellModel
            if model.tag == Tag.timerStartTime.rawValue {
                timeType = .start
                showTimePickerView()
            } else if model.tag == Tag.timerEndTime.rawValue {
                timeType = .end
                showTimePickerView()
            } else if model.tag == Tag.setttingColor.rawValue {
                let colorPicker = SettingColorViewController()
                colorPicker.delegate = self
                present(colorPicker, animated: true)
            }
        }
    }
}

extension TimerAddViewController: SettingColorViewControllerDelegate {
    func colorChanged(_ color: UIColor) {
        viewModel.setTimerColor(color)
        view.backgroundColor = color
        if let indexPath = didSelectIndexPath {
            tableView.reloadRows(at: [indexPath], with: .none)
        }
    }
}

extension TimerAddViewController: TimePickerViewDelegate {
    func timePickerView(hour: Int, minute: Int) {
        viewModel.setTimerTime(hour: hour, minute: minute, timeType: timeType)
        if let indexPath = didSelectIndexPath {
            tableView.reloadRows(at: [indexPath], with: .none)
        }
    }
    
    func quit() {
        didSelectIndexPath = nil
    }
}
